# -*- coding: utf-8 -*-

#

import socket, threading, time


class TcpServer(object):

    def __init__(self, bind, port):
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.bind((bind, port))
        self._socket.listen(5)

    def _reselve_and_report(self, sock, address):
        print 'Accept new connect from %s '% address[0]
        sock.send('Welcome!')
        num_not_data = 0
        while True:
            time.sleep(1)
            data = sock.recv(1024)
            if data == 'exit':
                break
            elif not data:
                num_not_data += 1
            else:
                num_not_data = 0
                sock.send('I resolve your info : %s' % data)
            if num_not_data >= 15:
                break
        sock.close()
        print 'Connection from %s:%s closed.' % address

    def listen(self):
        print 'waiting for accept'
        while True:
            sock, add = self._socket.accept()
            t = threading.Thread(target=self._reselve_and_report, args=(sock, add))
            t.start()


if __name__ == '__main__':
    tcp_server = TcpServer('127.0.0.1', 9090)
    tcp_server.listen()


